package com.google.project.server.servlet;

import java.io.IOException;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.project.server.PMF;
import com.google.project.server.entity.Document;

public class Upload extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// init the blog store service
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();
	private final BlobInfoFactory blobInfoFactory = new
	BlobInfoFactory(DatastoreServiceFactory.getDatastoreService());

	@SuppressWarnings("deprecation")
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse res)
			throws ServletException, IOException {
		
		int len = request.getContentLength();
		int mb = (1024 * 1024) * 10;
		if (len > mb) {
			throw new RuntimeException(
					"Sorry that file is too large. Try < 10240 or 10MB file");
		}

		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
		BlobKey blobKey = blobs.get("myFile");
		
		Document myDoc = new Document();
		
		myDoc.setDocumentName(request.getParameter("txtDocName"));
		myDoc.setDescription(request.getParameter("txtDescription"));
		myDoc.setForId(request.getParameter("forId"));
		myDoc.setType(request.getParameter("type"));
		myDoc.setCreatedOnDate(new Date().getTime());
		
		
		myDoc.setUrl("/serve?blob-key=" + blobKey.getKeyString());
		myDoc.setBlobKey(blobKey.getKeyString());
		
		BlobKey blob = new BlobKey(blobKey.getKeyString());
		BlobInfo blobInfo = blobInfoFactory.loadBlobInfo(blob);
		if(myDoc.getDocumentName() == null) {
			myDoc.setDocumentName(blobInfo.getFilename());
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(myDoc);
		} finally {
			pm.close();
		}

	}

}